/**
 * 文件名：AgentApiControllerTest<br/>
 * CopyRight (c) 2019-2030：<br/>
 * 创建人：wuxinchao
 * 日期：2022-05-18
 * 修改人：
 * 日期：
 * 描述：
 * 版本号：2.0
 */
package com.koala.work.yuntingche;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.junit.Test;

import java.util.*;

/**
 * 一句话功能简述
 *
 * @author wuxinchao
 * @since 2.0
 */
public class AgentApiControllerTest {

    private final String appkey = "5C877B980CF217F763B02C19";
    private final String secret = "82B7ADBC26AAC6A48C1FEEC151FE53F3";

    /**
     * 获取32位的随机字符串
     *
     * @return 一定长度的字符串
     */
    private String getNonce() {
        String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 32; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    @Test
    public void related() throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("ns", getNonce());
        map.put("ts", System.currentTimeMillis());
        map.put("appid", appkey);
        map.put("agentCity", "浙江省杭州市萧山区");
        map.put("agentAddr", "浙江省杭州市萧山区宁围街道111号");
        map.put("manager", "wxc");
        map.put("account", "737798942280220674");
        map.put("password", EncryptUtil.encrypt("Abc123456"));
        map.put("agentId", "100003");
        map.put("agentName", "12121212");
        map.put("sign", getSign(map, secret));
        System.out.println(JSONObject.toJSONString(map));
        String url = "http://10.67.172.206:30008/api/dealer/v2/api/agent/related";
        String ret = doPost(url, map);
        System.out.println(ret);
    }

    @Test
    public void cancel() throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("ns", getNonce());
        map.put("ts", System.currentTimeMillis());
        map.put("appid", appkey);
        map.put("agentId", "100003");
        map.put("sign", getSign(map, secret));
        System.out.println(JSONObject.toJSONString(map));
        String url = "http://10.67.172.206:30008/api/dealer/v2/api/agent/cancel";
        String ret = doPost(url, map);
        System.out.println(ret);
    }


    /**
     * 生成签名
     *
     * @param map 参数map
     * @param key 签名秘钥
     * @return 签名
     */
    private String getSign(final Map<String, Object> map, String key) {
        Set<String> keySet = map.keySet();
        String[] keyArray = keySet.toArray(new String[0]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            Object value = map.get(k);
            if (ObjectUtil.isEmpty(value)) {
                continue;
            }
            sb.append(k).append("=").append(value.toString()).append("&");
        }
        sb.append("secret=").append(key);
        return SecureUtil.md5(sb.toString()).toUpperCase();
    }


    public String getSign2(TreeMap<String, Object> map, String key) {
        map.put("secret", key);
        String url = URLUtil.buildQuery(map, null);
        return SecureUtil.md5(url.toString()).toUpperCase();
    }

    /**
     *
     */
    @Test
    public void test1224() {
        String zfcAll = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
        char[] zfc = zfcAll.toCharArray();
        String s = RandomUtil.randomStringUpper(32);
        System.out.println(s);
    }

    /**
     *
     */
    @Test
    public void test124() {
        TreeMap<String, Object> map = new TreeMap<>();
        map.put("A", "B");
        map.put("C", "C");
        map.put("B", "B");
        System.out.println(getSign(map, "123"));
        System.out.println(getSign2(map, "123"));
    }


    private String doPost(String url, Map<String, Object> param) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        Set<String> key = param.keySet();
        for (Iterator<String> it = key.iterator(); it.hasNext(); ) {
            String mapKey = (String) it.next();
            params.add(new BasicNameValuePair(mapKey, String.valueOf(param.get(mapKey))));
        }
        RequestConfig defaultRequestConfig = RequestConfig.custom()
                .setSocketTimeout(6000)
                .setConnectTimeout(6000)
                .setConnectionRequestTimeout(6000)
                .build();
        post.addHeader("ClientType", "16");
        post.setConfig(defaultRequestConfig);
        UrlEncodedFormEntity urfEntity;
        CloseableHttpResponse response = null;
        try {
            urfEntity = new UrlEncodedFormEntity(params, "utf-8");
            post.setEntity(urfEntity);
            HttpEntity entity1 = post.getEntity();
            response = httpClient.execute(post);
            HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                response.close();
            } catch (Exception e) {
            }
        }
    }
}
